package com.nageoffer.jobtrain.projects.mq.producer;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.nageoffer.jobtrain.common.rocketmq.base.BaseSendExtendDTO;
import com.nageoffer.jobtrain.common.rocketmq.base.MessageWrapper;
import com.nageoffer.jobtrain.common.rocketmq.producer.AbstractCommonSendProduceTemplate;
import com.nageoffer.jobtrain.projects.common.constant.RocketMQContent;
import com.nageoffer.jobtrain.projects.mq.event.OjQuestionSubmitEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 用户提交代码至 RocketMQ生产者
 * author：唐晨
 */
@Slf4j
@Component
public class OjQuestionSubmitProducer extends AbstractCommonSendProduceTemplate<OjQuestionSubmitEvent> {
    public OjQuestionSubmitProducer(@Autowired RocketMQTemplate rocketMQTemplate) {
        super(rocketMQTemplate);
    }

    @Override
    protected BaseSendExtendDTO buildBaseSendExtendParam(OjQuestionSubmitEvent messageSendEvent) {
        StringBuilder keys = new StringBuilder(messageSendEvent.getPhoneNumber() + ":" + messageSendEvent.getQuestionId());
        if (ObjectUtil.isNotNull(messageSendEvent.getContestId())) {
            keys.append(":" + messageSendEvent.getContestId());
        }
        return BaseSendExtendDTO.builder()
                .eventName("用户提交代码判题事件")
                // 使用（用户手机号 + 竞赛ID + 题目ID）作为幂等标识判断
                .keys(keys.toString())
                .topic(RocketMQContent.USER_OJ_QUESTION_SUBMIT_TOPIC_KEY)
                .sendTimeout(2000L)
                .build();
    }

    @Override
    protected Message<?> buildMessage(OjQuestionSubmitEvent messageSendEvent, BaseSendExtendDTO requestParam) {
        String keys = StrUtil.isEmpty(requestParam.getKeys()) ? UUID.randomUUID().toString() : requestParam.getKeys();
        return MessageBuilder
                .withPayload(new MessageWrapper(keys, messageSendEvent))
                .setHeader(MessageConst.PROPERTY_KEYS, keys)
                .setHeader(MessageConst.PROPERTY_TAGS, requestParam.getTag())
                .build();
    }
}
